#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define MAX_N_NIZA 100

void zameni(int p, int k);
long v_vrste(int i);
int a(int i, int j);
void a_dodela(int i, int j, int v);

int an[MAX_N_NIZA * 10]; //simulirana matrica cifara, nizom a[]
int n = 0, m = 0; //dimenzije  matrice



int main(int argc, char** argv) {
    int rnd_n_min = 0, rnd_n_max = 9; //najmanja i najveca cifra u matrici
    int i = 0, j = 0; //counters
    long vi, vj;

    printf("Unesti velicinu matrice (m,n<10):\n");
    scanf("%d %d", &m, &n);
    printf("Unesti opseg brojeva(0<=n<=9):\n");
    scanf("%d %d", &rnd_n_min, &rnd_n_max);
    printf("\n\n");

    while ((n > 0) && (n < 10) && (m > 0) && (m < (MAX_N_NIZA + 1)) && (rnd_n_min >= 0) && (rnd_n_min < rnd_n_max) && (rnd_n_max < 10)) {
        /*Ubacivanje random elemenata matrice*/
        for (i = 0; i < m; i++)
            for (j = 0; j < n; j++)
                a_dodela(i, j, ((rand() % (rnd_n_max - rnd_n_min + 1)) + rnd_n_min)); //vraca random vrednost u opsegu [rnd_min..rnd_max]

        //debug
        for (i = 0; i < m; printf("\n"), i++)
            for (j = 0; j < n; j++) printf(" %d", a(i, j));
        //debug_end

                    /*Obrada matrice*/
                for (i = 0; i < m - 1; i++) {

                    for (j = i + 1; j < m; j++) {
                        vi = v_vrste(i);
                                vj = v_vrste(j);
                        if (vi > vj) zameni(i, j);
                        }
                }

        printf("\n");
                /*Ispis (debuging)*/
        for (i = 0; i < m; printf("\n"), i++)

            for (j = 0; j < n; j++)
                    printf(" %d", a(i, j));


                    /*Ponavljanje upita*/
                    printf("Unesti velicinu matrice (m,n<10):\n");
                    scanf("%d %d", &m, &n);

                    printf("Unesti opseg brojeva(0<=n<=9):\n");
                    scanf("%d %d", &rnd_n_min, &rnd_n_max);
            }
    return (EXIT_SUCCESS);
}


//menja mesta vrstama 'p' i 'k' matrice 'a[][]'

void zameni(int p, int k) {
    int j;
    for (j = 0; j < n; j++) {

        int pom = a(k, j);
                a_dodela(k, j, (a(p, j)));
                a_dodela(p, j,pom);
    }
}

//vraca vrednost vrste 'i' matrice 'a[][]'

long v_vrste(int i) {
    long k = 1;
            int j;
            long p = 0;
    for (j = n - 1; j >= 0; k *= 10, j--)
            p += a(i, j) * k;

        return p;
    }

//simulira vracanje vrednosti iz mat a[i][j], a ustvari adresnom funkcijom vraca vrednosti iz niza an[]

int a(int i, int j) {
    int x = *(an + i * 10 + j);
    return x;
}
//simulira upisivanje vrednosti u mat a[i][j]
void a_dodela(int i, int j, int v) {
    *(an + i * 10 + j) = v;
}

